package com.xspace.android.imcommon.http;

import android.util.Log;

import com.google.gson.Gson;
import com.xspace.android.imcommon.entity.UserInfo;
import com.xspace.android.imcommon.utils.ImConstants;
import com.xspace.android.xafcommon.util.AppUtils;
import com.xspace.android.xafcommon.util.LogUtils;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.InputStream;

public class FriendDetailTask implements NetworkListener {
	private String uuid;
	private IFriendDetailResult requestResult;

	public FriendDetailTask(String uuid, IFriendDetailResult requestResult) {
		this.uuid = uuid;
		this.requestResult = requestResult;
	}

	@Override
	public void action(int actionCode, Object object) {
		switch (actionCode) {
		case NetworkListener.RECEIVE_STREAM:
			try {
				String result = AppUtils.parser((InputStream) object);
				LogUtils.i("fetch frienddetail response : %s" + result);
				parserContactList(result);
			} catch (Exception e) {
				this.requestResult.requestResult(null);
				LogUtils.i("FetchFriendsTask" + e + "");
			}
			break;
		case NetworkListener.REQUEST_TIMEOUT:
		case NetworkListener.STREM_EXCEPTION:
		case NetworkListener.APN_NOTEXIST:
			this.requestResult.requestResult(null);
			break;
		}
	}

	/**
	 * 解析网络联系人列表
	 * 
	 * @param result
	 * @throws Exception
	 */
	private void parserContactList(String result) throws Exception {
		UserInfo info = null;
		try {
			JSONTokener jsonParser = new JSONTokener(result);
			JSONObject returnObj = null;
			returnObj = (JSONObject) jsonParser.nextValue();
			int code = returnObj.getInt("code");
			if (code == 0) {
				Gson mGson = new Gson();
				info = mGson.fromJson(returnObj.getString("user"),
						UserInfo.class);
				info.uuid = uuid;
			}

		} catch (Exception e) {
			e.printStackTrace();

		}
		this.requestResult.requestResult(info);
	}

	/**
	 * 发送获取网络联系人请求
	 */
	public void sendFetchFriendsRequest() {
		String searchurl=ImConstants.getSearChUrl();
		Log.v("mRoster","searchurl:"+searchurl);
		ConnectorImpl conn = new ConnectorImpl(searchurl,
				buildFetchFriendsRequest(), this, ConnectorImpl.POST);
		ThreadPoolWrap.getThreadPool().executeTask(conn);
	}

	// 构造获取好友请求
	private String buildFetchFriendsRequest() {
		return "{uuid:\"" + uuid + "\",mobile:\"\"}";

	}

}
